import time
import os

def qmd2pdb(f, config_name):
    """convert the qmd format to pdb format"""
    time_now = time.strftime('%Y-%m-%d',time.localtime(time.time()))
    o = open(config_name + "_qmd.pdb", 'w')
    label = ["ATOM", "UNK"]

    o.write("""HEADER %s
REMARK    MADE BY DIRECT FORCE FIELD.
REMARK %s
"""%(config_name, time_now))

    for i in f:
        if len(i.split()) == 6 and i.startswith(' '):
            a = i.split()
            atom_name = a[1] + a[0]
            res = 1
            o.write("%-6s%5d  %-4s %3s  %4d  %8.3f%8.3f%8.3f\n"%(label[0],int(a[0]), atom_name, label[1], res, float(a[3]), float(a[4]), float(a[5])))
        if i.startswith("$END !ATOM"):
            o.close()
            return 0

def qmd2pdb_multi(file_name):
    """output all the configurations in qmd file"""
    f = open("%s.qmd"%file_name, 'r')
    counter = 0

    for i in f:
        if i.startswith("$ATOM"):
            config_name = file_name + "%d"%counter
            qmd2pdb(f, config_name)
            counter += 1
    f.close()

def scan_energy(file_name):
    """ Scan the qmd file and return the lowest energy"""
    energy_list = []

    p = os.popen('grep -A 1 "\$ENERGY" %s.qmd'%file_name, 'r')
    for i in p:
        if len(i.split()) == 2:
            energy_list.append(i.split()[0])
    p.close()

    b = float(energy_list[0])
    minimun_energy = energy_list[0]

    for i in energy_list:
        a = float(i)
        if a < b:
            b = float(a)
            minimun_energy = a
    return minimun_energy


def qmd2pdb_minimum(file_name):
    """This function is used to find the lowest energy configuration in qmd
    and output corresponding pdb file
    """
    minimum_energy = scan_energy(file_name)
    f = open("%s.qmd"%file_name, 'r')
    counter = 0

    for i in f:
        if i.startswith("$ATOM"):
            config_name = file_name + "%d"%counter
            qmd2pdb(f, config_name)
            counter += 1
        if i.strip().startswith("%s"%minimum_energy):
            os.system("cp %s_qmd.pdb %s_qm_opt.pdb"%(config_name, config_name))

    f.close()


if __name__ == "__main__":
    file_list = os.listdir('./')

    for i in file_list:
        if i[-3:] == 'qmd':
            file_name = i[:-4]
            qmd2pdb_minimum(file_name)

